#include <iostream>
#include <string>
#include <cstdlib>
#include <cerrno>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "tcp_err.hpp"

using namespace std;

void Usage(std::string name)
{
    std::cout << "使用错误！" << std::endl;
    std::cout << "./" << name << "port  " << "ip" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(USE_ERR);
    }
    //1.创建套接字
    uint16_t port = atoi(argv[1]);
    const std::string ip = argv[2];
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    inet_aton(ip.c_str(), &server.sin_addr);
    
    //2.请求连接

    int cnt = 5;
    while(connect(sock, (struct sockaddr*)&server, sizeof(server)) != 0)
    {
        sleep(1);
        cout << "连接失败！正在尝试重新链接...   剩余次数：" << cnt-- << endl;
        if(cnt <= 0) break;
    }

    if(cnt <= 0)
    {
        cerr << "connect error!" << endl;
        exit(CONNECT_ERR);
    }

    char buffer[1024];
    while(true)
    {
        string line;
        cout << "请输入消息：" ;
        getline(cin, line);

        write(sock, line.c_str(), line.size());

        ssize_t n = read(sock, buffer, sizeof(buffer)-1);

        if(n < 0)
        {
            cerr << "read error!" << strerror(errno) << endl;
            break;
        }
        else if(n == 0)
        {
            cerr << "server quit!" << endl;
            break;
        }
        else 
        {
            buffer[n] = 0;
            cout << "server echo >> " << buffer << endl;
        }

        
    }
    close(sock);

    return 0;
}